<template>
  <q-page class="q-pa-md">
    <q-btn class="float-right" color="primary" icon="arrow_back" outline title="返回" to="/" />
    <div class="q-pb-md text-h5">上架</div>
    <!--错误提示-->
    <q-banner class="text-white bg-red q-mb-md" dense inline-actions v-if="serverErrorMessage">
      {{ serverErrorMessage }}
      <template v-slot:action>
        <q-btn @click="serverErrorMessage = ''" dense flat icon="close" size="sm" />
      </template>
    </q-banner>
    <div class="row q-pt-sm q-col-gutter-sm">
      <div class="row col-12">
        <div class="col-12">
          <q-icon color="red" name="fas fa-asterisk" size="10px" />
          <span>仓库</span>
          <simple-filter-select :auto-select-first-option="$d.autoSelectFirstWh" :options="$d.whDropdownList"
            option-label="whName"
            :error="v$.whId.$error" :error-message="e$(v$.whId.$errors)"
            option-value="whId" v-model="$d.form.whId" :use-filter="false" @update:model-value="fLpnEnter" />
        </div>
      </div>
      <div class="row col-12">
        <div class="col-12">
          <q-icon color="red" name="fas fa-asterisk" size="10px" />
          <span>来源栈板</span>
          <q-input :error="v$.fLpn.$error" :error-message="e$(v$.fLpn.$errors)" :hide-bottom-space="true" dense
            clearable ref="fLpn" no-error-icon outlined square stack-label v-model="$d.form.fLpn"
            @keyup.enter="fLpnEnter" @focus="fx.ui.select" />
        </div>
        <div class="col-12">
          <q-icon color="red" name="fas fa-asterisk" size="10px" />
          <span>来源储位</span>
          <simple-filter-select :options="$d.locDropdownList" dense
            :error="v$.fLoc.$error" :error-message="e$(v$.fLoc.$errors)" no-error-icon v-model="$d.form.fLoc"
            :auto-select-first-option="$d.autoSelectFirstWh" :use-filter="false" ref="fLoc"
            @update:model-value="getSuggestedLocLites" />
        </div>
      </div>
      <div class="row col-12">
        <div class="col-12">
          <span>建议上架储位</span>
          <q-input readonly dense no-error-icon outlined square stack-label v-model="$d.suggestedLocDropdownList">
          </q-input>
        </div>
      </div>
      <div class="row col-12">
        <div class="col-12">
          <q-icon color="red" name="fas fa-asterisk" size="10px" />
          <span>上架储位</span>
          <q-input :error="v$.tLoc.$error" :error-message="e$(v$.tLoc.$errors)" :hide-bottom-space="true" dense
            clearable ref="tLoc" no-error-icon outlined square stack-label v-model="$d.form.tLoc"
            @focus="fx.ui.select" />
        </div>
      </div>
      <div class="row col-12">
        <div class="col-12">
          <q-icon color="red" name="fas fa-asterisk" size="10px" />
          <span>目的栈板</span>
          <q-input :error="v$.tLpn.$error" :error-message="e$(v$.tLpn.$errors)" :hide-bottom-space="true" dense
            clearable ref="fLpn" no-error-icon outlined square stack-label v-model="$d.form.tLpn"
            @focus="fx.ui.select" />
        </div>
      </div>
      <div class="row col-12">
        <div class="col-12">
          <q-btn class="full-width" color="primary" icon-right="fas fa-sign-in-alt" label="确定上架" @click="doPutaway"
            :loading="receiveInfoLoadingState" />
        </div>
      </div>
    </div>
  </q-page>
</template>

<script lang="ts">
export default {
  name: 'putawayStd'
}
</script>

<script lang="ts" setup>
import {computed, nextTick, reactive, ref} from 'vue'
import useVuelidate from '@vuelidate/core'
import {WmWhLite} from '@njt/wms/defs/basic/wh'
import {GetInvLocResp} from '@njt/wms/defs/inventory/invloc'
import _ from 'lodash'
import {playErrorSound, playSuccessSound} from '@njt/wms/helper/audio'
import {SuggestedPutawayLocLites} from '../../defs/putaway'

let serverErrorMessage = ref('')
let getSuggestedLocsLoadingState = ref(false)
let receiveInfoLoadingState = ref(false)

const $d = reactive({
  autoSelectFirstWh: false,
  form: {
    //仓库ID
    whId: null as number | null,
    //来源储位
    fLoc: null as string | null,
    //来源栈板
    fLpn: null as string | null,
    //上架储位
    tLoc: null as string | null | object,
    // 目的栈板
    tLpn: null as string | null
  },
  pageName: '/wms/work/putaway',
  whDropdownList: [] as WmWhLite[],
  locDropdownList: [] as string[],
  suggestedLocDropdownList: [] as string[]
})
const validators = $f.validators
const rules = {
  whId: {
    required: validators.required
  },
  fLpn: {
    required: validators.required
  },
  fLoc: {
    required: validators.required
  },
  tLoc: {
    required: validators.required
  },
  tLpn: {
    required: validators.required
  }
}
const v$ = useVuelidate(rules, computed(() => $d.form), {$autoDirty: true})
const fLpnEnter = function () {
  $d.form.fLoc = null
  if ($d.form.whId && $d.form.fLpn) {
    let params = {
      whId: $d.form.whId,
      lpn: $d.form.fLpn,
      ifShowZeroInvItem: false,
      pageNo: 1,
      pageSize: 10000
    }
    getSuggestedLocsLoadingState.value = true
    $f.axios
      .get<GetInvLocResp>('/wms/inv/inventory/get-inv-loc-list', {params: params})
      .then((resp) => {
        $d.locDropdownList = _.uniq(_.map(resp.data.invLocList, 'loc')) as string[]
        if ($d.locDropdownList.length === 1) {
          $d.form.fLoc = $d.locDropdownList[0]
          getSuggestedLocLites()
        }
      })
      .catch((err) => {
        $f.ui.showNotifyFailed($f.getAxiosErrMsg(err))
      })
      .finally(() => {
        getSuggestedLocsLoadingState.value = false
        void nextTick(() => {
          tLoc.value?.focus()
        })
      })
  }
}

//获取建议上架储位简要列表
const getSuggestedLocLites = function (val?: string) {
  if ($d.form.fLpn) {
    $d.form.tLpn = $d.form.fLpn
  }
  $d.suggestedLocDropdownList = []
  $d.form.tLoc = null
  if (val === 'clear' || $d.form.fLpn === null || $d.form.fLoc === null) {
    return
  }
  getSuggestedLocsLoadingState.value = true
  let params = {
    whId: $d.form.whId,
    fLpn: $d.form.fLpn,
    floc: $d.form.fLoc
  }
  $f.axios
    .get<SuggestedPutawayLocLites[]>('/wms/rule/pazone/get-suggested-putaway-loc-lites', {params: params})
    .then((resp) => {
      $d.suggestedLocDropdownList = _.map(resp.data, 'loc') as string[]
    })
    .catch((err) => {
      $f.ui.showNotifyFailed($f.getAxiosErrMsg(err))
    })
    .finally(() => {
      getSuggestedLocsLoadingState.value = false
      void nextTick(() => {
        tLoc.value?.focus()
      })
    })
}

const doPutaway = function () {
  serverErrorMessage.value = ''
  void v$.value
    .$validate()
    .then((valRes) => {
      if (valRes) {
        receiveInfoLoadingState.value = true
        $f.axios
          .post('/wms/inv/inventory/putaway-by-pda', $d.form)
          .then(() => {
            // 储存使用的仓库
            window.localStorage.setItem('wh_id:' + $d.pageName , String($d.form.whId as number))
            // 确保不要再验证
            $d.form.fLpn = null
            $d.form.fLoc = null
            $d.form.tLoc = null
            $d.form.tLpn = null
            $d.locDropdownList = []
            $d.suggestedLocDropdownList = []
            v$.value.$reset()
            fLpn.value?.focus()
            $f.ui.showNotifySucceeded('上架成功')
            playSuccessSound()
          })
          .catch((err) => {
            playErrorSound()
            serverErrorMessage.value = $f.getAxiosErrMsg(err)
          })
          .finally(() => {
            receiveInfoLoadingState.value = false
          })
      } else {
        playErrorSound()
      }
    })
}

// 仓库下拉
void $f.lst.getWmWhSimpleList()
  .then((resp) => {
    $d.whDropdownList = resp
  })

// 查找页面存储
let whId = window.localStorage.getItem('wh_id:' + $d.pageName)
if (whId) {
  $d.form.whId = parseInt(whId)
} else {
  $d.autoSelectFirstWh = true
}

const tLoc = ref<HTMLElement>()
const fLpn = ref<HTMLElement>()
const e$ = $f.getFieldErrStr
const fx = $f
</script>

<style scoped>

</style>
